import { useAuthStore } from '@/store'

function getMessage(msg, txt) {
  const result = msg ?? txt;
  console.log(result);
  // $modal.message({ message: result, type: "error" });
  return result;
}

let isConfirming = false;

export function resolveResError(code, message) {
  let result;
  const errorMessageMap = {
    401: '无访问权限',
    403: '请求被拒绝',
    404: '请求资源或接口不存在',
    500: '服务器发生异常'
  };

  switch (code) {
    case 60104:
      result = message ?? "登录已过期";
      if (isConfirming) return false; // 明确返回false
      isConfirming = true;
      $modal.confirm(
        '登录已过期，是否重新登录？',
        '登录提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          await useAuthStore().logout();
          window.location.href = '/login'
          $modal.message({ message: '已退出登录!', type: 'success' });
        })
        .catch(() => {
          // 不需要额外处理，finally会重置状态
        })
        .finally(() => {
          isConfirming = false;
        });
      return false;
    case 401:
    case 403:
    case 404:
    case 500:
      result = getMessage(message, errorMessageMap[code]);
      break;
    default:
      let codeX = code ? `【${code}】: 未知异常!` : `未知异常!`;
      result = getMessage(message, codeX);
      break;
  }
  return result;
}